var gulp = require("gulp");
var watch = require("gulp-watch");
var sass = require("gulp-sass"); //sass编译器
var autoprefixer = require("gulp-autoprefixer"); //自动添加css前缀
var minifycss = require("gulp-minify-css"); //压缩css
var uglify = require("gulp-uglify"); //js代码压缩
var jshint = require("gulp-jshint"); //js代码校验
var rename = require("gulp-rename"); //文件重命名
var notify = require("gulp-notify"); //更改提醒
var concat = require("gulp-concat"); //文件合并
var livereload = require("gulp-livereload"); //修改js，css，html时页面自动刷新

// css编译压缩
gulp.task("css", function() {
  return gulp.src("public/dev/sass/*.scss") //设置要编译的文件路径
    .pipe(sass())
    .pipe(autoprefixer({
      browsers: ['last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 2.3'],
      cascade: true,
      remove: true
    }))
    .pipe(gulp.dest("public/dev/css")) //设置编译后文件放置路径
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(minifycss())
    .pipe(gulp.dest("public/css")) //设置编译压缩后文件放置路径
    .pipe(notify({
      message: 'css编译完成'
    }));
});

// js校验压缩
gulp.task("js", function() {
  return gulp.src("public/dev/js/*.js") //设置需要校验的文件路径
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(uglify())
    .pipe(gulp.dest('public/js')) //设置校验压缩后文件放置路径
    .pipe(notify({
      message: 'javascript 合并压缩完成'
    }));
});

// 开启监听css和js变化
gulp.task("watch", function() {
  gulp.watch("public/dev/sass/*.scss", ["css"]);
  gulp.watch("public/dev/js/*.js", ["js"]);
  livereload.listen();
  gulp.watch(["public/css/*", "public/js/*", "views/*"]).on("change", livereload.changed);
})

// 默认执行任务
gulp.task('default', function() {
  gulp.start('css', 'js', 'watch');
});